package com.stock.demo.function.start.view;

import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.stock.demo.MainActivity;
import com.stock.demo.R;
import com.stock.demo.framework.ui.TipType;
import com.stock.demo.framework.ui.activity.BaseActivity;
import com.stock.demo.framework.ui.view.EditTextWithDelBtn;
import com.stock.demo.function.start.presenter.LoginPresenter;
import com.stock.demo.function.start.presenter.LoginPresenterImpl;
import com.stock.demo.util.CommonUtils;
import com.stock.demo.util.SettingUtils;

import java.lang.reflect.Field;

/**
 * Created by XuZhaoyu on 2017/5/15.
 */

public class LoginActivity extends BaseActivity implements LoginView, EditTextWithDelBtn.OnContentChangeListener {

    private int statusBarHeight;
    private int keyboardHeight;
    private boolean isShowKeyboard;

    private ImageView mIvUsername;
    private ImageView mIvPassword;
    private EditTextWithDelBtn mEtUsername;
    private EditTextWithDelBtn mEtPassword;
    private Button mBtnLogin;
    private ImageView mIvUserIcon;
    private LinearLayout mLinearLayout;
    private RelativeLayout mRelativeLayout;
    private TextView mTvRegister;
    private TextView mTvForgetPassword;
    private LoginPresenter mPresenter;

    public static void startAction(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        context.startActivity(intent);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (SettingUtils.checkAutoLogin()) {
            MainActivity.startAction(this);
            finish();
        } else {
            setContentView(R.layout.activity_login);
            initView();
            initData();
            setListener();
        }
    }

    private void initView() {
        mRelativeLayout = (RelativeLayout) findViewById(R.id.rl_login);
        mLinearLayout = (LinearLayout) findViewById(R.id.ll_login);
        mIvUsername = (ImageView) findViewById(R.id.iv_login_id);
        mIvPassword = (ImageView) findViewById(R.id.iv_login_pw);
        mEtUsername = (EditTextWithDelBtn) findViewById(R.id.et_login_id);
        mEtPassword = (EditTextWithDelBtn) findViewById(R.id.et_login_pw);
        mBtnLogin = (Button) findViewById(R.id.btn_login);
        mIvUserIcon = (ImageView) findViewById(R.id.iv_login_head);
        mTvRegister = (TextView) findViewById(R.id.tv_login_register);
        mTvForgetPassword = (TextView) findViewById(R.id.tv_login_forgetpw);
    }

    private void initData() {
        statusBarHeight = getStatusBarHeight(getApplicationContext());
        mRelativeLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                mRelativeLayout.getViewTreeObserver().addOnGlobalLayoutListener(globalLayoutListener);
            }
        }, 300);
        mPresenter = new LoginPresenterImpl(this);
    }

    private void setListener() {
        mEtUsername.setOnContentChangeListener(this);
        mEtPassword.setOnContentChangeListener(this);
        mTvRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RegisterActivity.startAction(LoginActivity.this);
            }
        });
        mBtnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkLoginData()) {
                    mPresenter.login(mEtUsername.getText(), mEtPassword.getText());
                } else {
                    showTip(TipType.ERROR, "请输入账号及密码");
                }
            }
        });
    }

    private boolean checkLoginData() {
        return (!TextUtils.isEmpty(mEtUsername.getText())) && (!TextUtils.isEmpty(mEtPassword.getText()));
    }

    public static int getStatusBarHeight(Context context) {
        try {
            Class<?> c = Class.forName("com.android.internal.R$dimen");
            Object obj = c.newInstance();
            Field field = c.getField("status_bar_height");
            int x = Integer.parseInt(field.get(obj).toString());
            return context.getResources().getDimensionPixelSize(x);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    private int getNavigationBarHeight() {
        Resources resources = getApplicationContext().getResources();
        int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
        return resources.getDimensionPixelSize(resourceId);
    }

    private ViewTreeObserver.OnGlobalLayoutListener globalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {
            // 应用可以显示的区域。此处包括应用占用的区域，
            // 以及ActionBar和状态栏，但不含设备底部的虚拟按键。
            Rect r = new Rect();
            mRelativeLayout.getWindowVisibleDisplayFrame(r);
            // 屏幕高度。这个高度不含虚拟按键的高度
            int screenHeight = mRelativeLayout.getRootView().getHeight() - getNavigationBarHeight();
            int heightDiff = screenHeight - (r.bottom - r.top);
            // 在不显示软键盘时，heightDiff等于状态栏的高度
            // 在显示软键盘时，heightDiff会变大，等于软键盘加状态栏的高度。
            // 所以heightDiff大于状态栏高度时表示软键盘出现了，
            // 这时可算出软键盘的高度，即heightDiff减去状态栏的高度
            if (keyboardHeight == 0 && heightDiff > statusBarHeight) {
                keyboardHeight = heightDiff - statusBarHeight;
            }
            if (isShowKeyboard) {
                // 如果软键盘是弹出的状态，并且heightDiff小于等于状态栏高度，
                // 说明这时软键盘已经收起
                if (heightDiff <= statusBarHeight) {
                    isShowKeyboard = false;
                    onHideKeyboard();
                }
            } else {
                // 如果软键盘是收起的状态，并且heightDiff大于状态栏高度，
                // 说明这时软键盘已经弹出
                if (heightDiff > statusBarHeight) {
                    isShowKeyboard = true;
                    onShowKeyboard();
                }
            }
        }
    };

    private void onShowKeyboard() {
        //处理软键盘弹出的回调
        PropertyValuesHolder p1 = PropertyValuesHolder.ofFloat("scaleX", 1f, 0f);
        PropertyValuesHolder p2 = PropertyValuesHolder.ofFloat("scaleY", 1f, 0f);
        ObjectAnimator.ofPropertyValuesHolder(mIvUserIcon, p1, p2).setDuration(300).start();
        ObjectAnimator.ofFloat(mLinearLayout, "translationY", 0f, -CommonUtils.dp2px(150)).setDuration(300).start();
        mTvRegister.setVisibility(View.GONE);
        mTvForgetPassword.setVisibility(View.VISIBLE);
    }

    private void onHideKeyboard() {
        PropertyValuesHolder p1 = PropertyValuesHolder.ofFloat("scaleX", 0f, 1f);
        PropertyValuesHolder p2 = PropertyValuesHolder.ofFloat("scaleY", 0f, 1f);
        ObjectAnimator.ofPropertyValuesHolder(mIvUserIcon, p1, p2).setDuration(300).start();
        ObjectAnimator.ofFloat(mLinearLayout, "translationY", -CommonUtils.dp2px(150), 0f).setDuration(300).start();
        mTvRegister.setVisibility(View.VISIBLE);
        mTvForgetPassword.setVisibility(View.GONE);
    }


    @Override
    public void beforeContentChange(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void OnContentChange(CharSequence s, int start, int before, int count) {
        if (mEtUsername.getText().length() > 0) {
            mIvUsername.setImageResource(R.mipmap.login_icon_user_focused);
        } else {
            mIvUsername.setImageResource(R.mipmap.login_icon_user);
        }
        if (mEtPassword.getText().length() > 0) {
            mIvPassword.setImageResource(R.mipmap.login_icon_password_focused);
        } else
            mIvPassword.setImageResource(R.mipmap.login_icon_password);
        if (mEtUsername.getText().length() > 0 && mEtPassword.getText().length() > 0) {
            mBtnLogin.setTextColor(getResources().getColor(R.color.colorWhite));
            mBtnLogin.setClickable(true);
        } else {
            mBtnLogin.setTextColor(getResources().getColor(R.color.colorBtnHint));
            mBtnLogin.setClickable(false);
        }
    }

    @Override
    public void afterContentChange(Editable s) {

    }

    @Override
    public void onLogin(boolean isSuccess) {
        if (isSuccess) {
            MainActivity.startAction(this);
            finish();
        } else {
            showTip(TipType.ERROR, "用户名或密码错误");
        }
    }
}
